package com.ssy.lingxi.marketing.serviceimpl.feign;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.model.bo.MemberAndRoleIdBO;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.marketing.api.model.request.GoodsCartRequest;
import com.ssy.lingxi.marketing.api.model.request.GoodsCartSkuItemRequest;
import com.ssy.lingxi.marketing.api.model.request.ProductTagReq;
import com.ssy.lingxi.marketing.api.model.response.GoodsActivityDetail;
import com.ssy.lingxi.marketing.api.model.response.GoodsCartResponse;
import com.ssy.lingxi.marketing.api.model.response.ProductTagResp;
import com.ssy.lingxi.marketing.entity.activity.ActivityGoodsSubsidiaryDO;
import com.ssy.lingxi.marketing.model.bo.ActivityGoodsDetailBO;
import com.ssy.lingxi.marketing.model.bo.ActivityGoodsProductBO;
import com.ssy.lingxi.marketing.model.bo.ActivityGoodsTagBO;
import com.ssy.lingxi.marketing.model.constant.CommonBooleanEnum;
import com.ssy.lingxi.marketing.repository.ActivityGoodsSubsidiaryRepository;
import com.ssy.lingxi.marketing.service.feign.IActivityGoodsFeignService;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityGoodsTagAndPriceComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityQueryComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动商品内部接口服务类实现类
 * @author yzc
 * @version 2.0.0
 * @date 2021/9/2
 */
@Slf4j
@Service
public class ActivityGoodsFeignServiceImpl implements IActivityGoodsFeignService {

    @Resource
    private ActivityQueryComponent activityQueryComponent;
    @Resource
    private ActivityGoodsTagAndPriceComponent activityGoodsTagAndPriceComponent;
    @Resource
    private ActivityGoodsSubsidiaryRepository goodsSubsidiaryRepository;

    @Override
    public Wrapper<List<ProductTagResp>> listActivityGoodsProductTag(ProductTagReq req) {
        MemberAndRoleIdBO memberAndRoleIdBO = null;
        if (Objects.nonNull(req.getMemberId()) && Objects.nonNull(req.getRoleId())) {
            memberAndRoleIdBO = new MemberAndRoleIdBO(req.getMemberId(), req.getRoleId());
        }
        Long shopId = req.getShopId();
        List<Long> productIds = req.getProductIds();
        if (Objects.isNull(shopId)) {
            return Wrapper.success(new ArrayList<>());
        }
        if (CollectionUtil.isEmpty(productIds)) {
            return Wrapper.success(new ArrayList<>());
        }

        // 活动商品
        List<ActivityGoodsDetailBO> activityGoodsBOList = activityQueryComponent.selectCheckActivityExecutingGoodsByProduct(memberAndRoleIdBO, shopId, productIds);
        //过滤不显示的活动(商品服务搜索功能不显示拼团商品)
        if(CollectionUtil.isNotEmpty(req.getFilterActivityType())&&CollectionUtil.isNotEmpty(activityGoodsBOList)){
            activityGoodsBOList=activityGoodsBOList.stream().filter(o ->!req.getFilterActivityType().contains(o.getActivityBO().getActivityType())).collect(Collectors.toList());
        }
        List<ActivityGoodsProductBO> goodsProductBOList = activityGoodsTagAndPriceComponent.handProductTag(activityGoodsBOList);
        List<ProductTagResp> resultList = goodsProductBOList.stream().map(e -> {
            ProductTagResp productTagResp = new ProductTagResp();
            productTagResp.setProductId(e.getProductId());
            productTagResp.setPreferentialPrice(e.getProductPreferentialPrice());
            //活动标签去重
            productTagResp.setTagList(e.getTotalTagList().stream().map(ActivityGoodsTagBO::getActivityTypeTag).distinct().collect(Collectors.toList()));
            return productTagResp;
        }).collect(Collectors.toList());

        return Wrapper.success(resultList);
    }

    private List<GoodsCartResponse> buildSubGoodsResponseList(List<GoodsCartSkuItemRequest> subGoodsReqList){
        if(CollectionUtil.isNotEmpty(subGoodsReqList)) {
            return subGoodsReqList.stream().map(o ->{
                GoodsCartResponse subGoods = new GoodsCartResponse();
                subGoods.setCanUseCoupon(CommonBooleanEnum.NO.getCode());
                subGoods.setSkuId(o.getSkuId());
                subGoods.setParentSkuId(o.getParentSkuId());
                subGoods.setIsMain(o.getIsMain());
                subGoods.setGroupNo(o.getGroupNo());
                return subGoods;
            }).collect(Collectors.toList());
        }
        return null;
    }

    public static String generateKey(Object... str){
        Object first=str[0];
        if(first==null){
            return "";
        }
        StringBuilder builder=new StringBuilder(first.toString());
        Arrays.stream(str).skip(1).forEach(o -> builder.append("_").append(o == null ? "" : o.toString()));
        return builder.toString();
    }

    @Override
    public Wrapper<List<GoodsCartResponse>> listActivityGoodsCart(GoodsCartRequest req) {
        log.info("购物车查询商品活动listActivityGoodsCart input:{}", JSONUtil.toJsonStr(req));
        MemberAndRoleIdBO memberAndRoleIdBO = new MemberAndRoleIdBO(req.getMemberId(), req.getRoleId());
        Long shopId = req.getShopId();
        Long memberId = req.getMemberId();
        Long roleId = req.getRoleId();

        // 每个主商品的活动
        List<ActivityGoodsDetailBO> activityGoodsBOList = new ArrayList<>();
        List<Long> mainSkuIds = req.getSkuList().stream().filter(GoodsCartSkuItemRequest::getIsMain).map(GoodsCartSkuItemRequest::getSkuId).distinct().collect(Collectors.toList());
        for (Long skuId : mainSkuIds) {
            // 活动商品
            List<ActivityGoodsDetailBO> goodsBOList = activityQueryComponent.selectCheckActivityExecutingGoodsByProductSku(memberAndRoleIdBO, shopId, skuId);
            activityGoodsBOList.addAll(goodsBOList);
        }
        //相同主商品的子商品列表map
        Map<String, List<GoodsCartSkuItemRequest>> sameMainSKuMap = req.getSkuList().stream().filter(o -> o.getParentSkuId() != null).collect(Collectors.groupingBy(o -> generateKey(o.getParentSkuId(),o.getGroupNo())));
        //相同sku主商品列表map
        Map<Long, List<GoodsCartSkuItemRequest>> mainSKuMap = req.getSkuList().stream().filter(GoodsCartSkuItemRequest::getIsMain).collect(Collectors.groupingBy(o ->o.getSkuId()));

        // 每个店铺的商品
        List<GoodsCartResponse> responseList = new ArrayList<>();
        // 每个商品的活动
        Map<Long, List<ActivityGoodsDetailBO>> goodsActivityMap = activityGoodsBOList.stream().collect(Collectors.groupingBy(ActivityGoodsDetailBO::getSkuId));

        // 处理的商品
        List<GoodsCartResponse> handActivityGoodsList = new ArrayList<>();
        for (Map.Entry<Long, List<ActivityGoodsDetailBO>> goodsActivityEntry : goodsActivityMap.entrySet()) {
            List<GoodsCartSkuItemRequest> cartMainSkuReqs = mainSKuMap.get(goodsActivityEntry.getKey());
            // 每个活动
            List<GoodsActivityDetail> goodsActivityDetailList = activityGoodsTagAndPriceComponent.handleCartSkuTag(memberId, roleId, shopId, goodsActivityEntry.getValue());
            boolean isSwapSku = goodsActivityDetailList.stream().anyMatch(o -> ActivityTypeEnum.SWAP.getCode().equals(o.getActivityType()));
            boolean isSetmealSku = goodsActivityDetailList.stream().anyMatch(o -> ActivityTypeEnum.SET_MEAL.getCode().equals(o.getActivityType()));
            for(GoodsCartSkuItemRequest cartMainSkuReq: cartMainSkuReqs) {
                //step1:构建返回参数
                GoodsCartResponse goodsCartResponse = new GoodsCartResponse();
                goodsCartResponse.setSkuId(goodsActivityEntry.getKey());
                goodsCartResponse.setIsMain(cartMainSkuReq.getIsMain());
                goodsCartResponse.setActivityType(cartMainSkuReq.getActivityType());
                goodsCartResponse.setGroupNo(cartMainSkuReq.getGroupNo());
                // 个人限购
                Integer restrictMinNum = goodsActivityEntry.getValue().stream().map(ActivityGoodsDetailBO::getRestrictNum).min(Comparator.comparing(e -> e)).orElse(0);
                goodsCartResponse.setRestrictMinNum(restrictMinNum);

                // 判断每个活动是否优惠券为同一值
                if (CollectionUtils.isEmpty(goodsActivityDetailList)) {
                    goodsCartResponse.setTopActivityDetail(null);
                    goodsCartResponse.setActivityDetails(Collections.emptyList());
                } else {
                    // 可用优惠券
                    GoodsActivityDetail goodsActivityDetail = goodsActivityDetailList.get(0);
                    long count = goodsActivityDetailList.stream().map(GoodsActivityDetail::getCanUseCoupon).distinct().count();
                    if (count == 1) {
                        goodsCartResponse.setCanUseCoupon(goodsActivityDetail.getCanUseCoupon());
                    } else {
                        goodsCartResponse.setCanUseCoupon(CommonBooleanEnum.NO.getCode());
                    }

                    //如果sku参与了换购，但是购物车标识非换购，则设置参与活动列表未空
                    if(isSwapSku&&(goodsCartResponse.getActivityType()==null|| !ActivityTypeEnum.SWAP.getCode().equals(goodsCartResponse.getActivityType()))){
                        goodsCartResponse.setActivityDetails(Collections.emptyList());
                    }else if(isSetmealSku&&(goodsCartResponse.getActivityType()==null|| !ActivityTypeEnum.SET_MEAL.getCode().equals(goodsCartResponse.getActivityType()))){
                        goodsCartResponse.setActivityDetails(Collections.emptyList());
                    }else {
                        goodsCartResponse.setActivityDetails(goodsActivityDetailList);
                    }
                }

                handActivityGoodsList.add(goodsCartResponse);

                //step2:如果主商品参与换购活动，查询子商品的换购价
                List<GoodsActivityDetail> subActivityList = goodsActivityDetailList.stream().filter(o -> ActivityTypeEnum.containSwapOrSetMeal(o.getActivityType())).collect(Collectors.toList());
                //获得主商品对应的子商品请求列表
                List<GoodsCartSkuItemRequest> goodsCartSkuItemRequests = sameMainSKuMap.get(generateKey(cartMainSkuReq.getSkuId(),cartMainSkuReq.getGroupNo()));
                Boolean isSwapActivity = Boolean.FALSE;
                if (CollectionUtil.isNotEmpty(subActivityList) && CollectionUtil.isNotEmpty(goodsCartSkuItemRequests)) {
                    ActivityGoodsDetailBO mainJoinActivity = goodsActivityEntry.getValue().stream().filter(o -> o.getActivityBO().getActivityType().equals(ActivityTypeEnum.SWAP.getCode())).findFirst().orElse(null);
                    //如果购物车标识主商品参与了换购
                    if (mainJoinActivity != null && ActivityTypeEnum.SWAP.getCode().equals(cartMainSkuReq.getActivityType())) {
                        //查询换购商品的价格
                        List<ActivityGoodsSubsidiaryDO> subsidiaryDOS = goodsSubsidiaryRepository.findByActivityGoodsId(mainJoinActivity.getId());
                        if (CollectionUtil.isNotEmpty(subsidiaryDOS)) {
                            List<Long> sameMainSubSkuList = goodsCartSkuItemRequests.stream().map(o -> o.getSkuId()).collect(Collectors.toList());
                            List<GoodsCartResponse> subGoodsList = subsidiaryDOS.stream()
                                    .filter(f -> sameMainSubSkuList.contains(f.getSkuId()))
                                    .map(o -> {
                                        GoodsCartResponse subGoods = new GoodsCartResponse();
                                        subGoods.setCanUseCoupon(CommonBooleanEnum.NO.getCode());
                                        subGoods.setSkuId(o.getSkuId());
                                        subGoods.setParentSkuId(cartMainSkuReq.getSkuId());
                                        subGoods.setPrice(o.getSwapPrice());
                                        subGoods.setIsMain(Boolean.FALSE);
                                        subGoods.setGroupNo(cartMainSkuReq.getGroupNo());
                                        return subGoods;
                                    }).collect(Collectors.toList());
                            handActivityGoodsList.addAll(subGoodsList);
                            isSwapActivity = Boolean.TRUE;
                        }
                    }
                }
                //如果非换购活动，填充子商品对象
                if (!isSwapActivity) {
                    //子商品未参与换购或套餐
                    List<GoodsCartResponse> goodsCartResponses = buildSubGoodsResponseList(goodsCartSkuItemRequests);
                    if (goodsCartResponses != null) {
                        handActivityGoodsList.addAll(goodsCartResponses);
                    }
                }
            }
        }

        //step3:分组
        for (GoodsCartResponse goodsCartResponse : handActivityGoodsList) {
            if(!goodsCartResponse.getIsMain()){continue;}
            if (goodsCartResponse.getActivityDetails().size() == 1) {
                goodsCartResponse.setTopActivityDetail(goodsCartResponse.getActivityDetails().get(0));
                goodsCartResponse.setActivityDetails(Collections.emptyList());
            } else {
                /*叠加促销时的商品顶部排序：
                    1、第一优先排序 满量/满额；
                    2、第二优先排序 特价/直降/折扣；
                    3、第三优先排序 多件、组合；
                    4、第四优先排序 换购；
                */
                Iterator<GoodsActivityDetail> iterator = goodsCartResponse.getActivityDetails().iterator();
                while (iterator.hasNext()) {
                    GoodsActivityDetail next = iterator.next();
                    if (ActivityTypeEnum.FULL_QUANTITY.getCode().equals(next.getActivityType())
                            || ActivityTypeEnum.FULL_MONEY.getCode().equals(next.getActivityType())) {
                        goodsCartResponse.setTopActivityDetail(next);
                        iterator.remove();
                        break;
                    }else if(ActivityTypeEnum.SPECIAL_OFFER.getCode().equals(next.getActivityType())
                            || ActivityTypeEnum.PLUMMET.getCode().equals(next.getActivityType())
                            || ActivityTypeEnum.DISCOUNT.getCode().equals(next.getActivityType())){
                        goodsCartResponse.setTopActivityDetail(next);
                        iterator.remove();
                        break;
                    }else if(ActivityTypeEnum.MORE_PIECE.getCode().equals(next.getActivityType())
                            || ActivityTypeEnum.COMBINATION.getCode().equals(next.getActivityType())){
                        goodsCartResponse.setTopActivityDetail(next);
                        iterator.remove();
                        break;
                    }else if(ActivityTypeEnum.SWAP.getCode().equals(next.getActivityType())){
                        goodsCartResponse.setTopActivityDetail(next);
                        iterator.remove();
                        break;
                    }
                }
            }
        }
        responseList.addAll(handActivityGoodsList) ;
        return Wrapper.success(responseList);
    }

    @Override
    public Wrapper<List<ProductTagResp>> getPreferentialPrice(ProductTagReq req) {
        return Wrapper.success(activityGoodsTagAndPriceComponent.getPreferentialPrice(req.getShopId(), req.getProductIds()));
    }

}
